﻿using SketchUpAPI.NET.Enums;
using SketchUpAPI.NET.SketchUp.Exception;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace SketchUpAPI.NET.Objects
{
    /// <summary>
    /// 物体集合
    /// </summary>
    /// <remarks>对 SketchUpAPI 中的 SUEntityListRef 的包装</remarks>
    public class EntityList : ObjectBase, IEnumerable<Entity>
    {
        #region API 函数
        /// <summary>
        /// 创建物件集合
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        [DllImport(LIB)]
        static extern SUResult SUEntityListCreate(out IntPtr list);

        /// <summary>
        /// 释放资源
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        [DllImport(LIB)]
        static extern SUResult SUEntityListRelease(ref IntPtr list);

        /// <summary>
        /// 迭代器
        /// </summary>
        /// <param name="list"></param>
        /// <param name="iterator"><see cref="EntityListIterator"/></param>
        /// <returns></returns>
        [DllImport(LIB)]
        static extern SUResult SUEntityListBegin(IntPtr list, out IntPtr iterator);

        /// <summary>
        /// 物体个数
        /// </summary>
        /// <param name="list"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        [DllImport(LIB)]
        static extern SUResult SUEntityListSize(IntPtr list, out long count);
        #endregion

        /// <summary>
        /// 物体个数
        /// </summary>
        public int Count
        {
            get
            {
                SketchUpExceptionHelper.ThrowSUResult(SUEntityListSize(Id, out long count));
                return (int)count;
            }
        }

        public EntityList()
        {
            SketchUpExceptionHelper.ThrowSUResult(SUEntityListCreate(out Id));
        }

        internal EntityList(IntPtr id) => Id = id;

        public override void Dispose()
        {
            SketchUpExceptionHelper.ThrowSUResult(SUEntityListRelease(ref Id));
        }

        public IEnumerator<Entity> GetEnumerator()
        {
            SketchUpExceptionHelper.ThrowSUResult(SUEntityListBegin(Id, out IntPtr iter));
            return new EntityListIterator(iter);
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}